package com.example.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.gulimall.cart.feign.ProductFeignService;
import com.example.gulimall.cart.interceptor.CartInterceptor;
import com.example.gulimall.cart.service.CartService;
import com.example.gulimall.cart.vo.Cart;
import com.example.gulimall.cart.vo.CartItem;
import com.example.gulimall.cart.vo.SkuInfoVo;
import com.example.gulimall.cart.vo.UserInfoTo;
import com.warren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    private final String CART_PREFIX = "gulimall:cart:";

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 添加到购物车
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String,Object,Object> cartPos = getCartOps();
        String res = (String) cartPos.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            //表示购物车没有这件商品，添加新商品到购物车
            CartItem cartItem = new CartItem();
            //1. 远程查询当前要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData2("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                cartItem.setSkuId(skuId);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
            }, executor);

            //2. 远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItem);
            cartPos.put(skuId.toString(),s);
            return cartItem;
        }else {
            CartItem cartItem = new CartItem();
            //购物车有此商品，修改数量极客
            cartItem = JSON.parseObject(res,CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartPos.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物车操作对象
     * @return
     */
    private BoundHashOperations<String,Object,Object> getCartOps(){
        UserInfoTo  userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            //gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else{
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String,Object,Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 获取购物车信息
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String)cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    /**
     * 获取整个购物车
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException{
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null){
            //1.登录状态
            String cartkey = CART_PREFIX + userInfoTo.getUserId();
            //2.如果临时购物车的数据还没有合并，那么久合并数据并清空临时购物车
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            //有临时数据需要合并
            if (tempCartItems != null && tempCartItems.size() > 0){
                for(CartItem item : tempCartItems){
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清空临时购物车的数据
                clearCart(tempCartKey);
            }
            //3. 获取的登录后的购物车[包含合并过来的临时购物车的数据，和登录后的购物车的数据]
            List<CartItem> cartItems = getCartItems(cartkey);
            cart.setItems(cartItems);
        }else{
            //未登录状态
            String cartkey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有的购物项
            List<CartItem> cartItems = getCartItems(cartkey);
            cart.setItems(cartItems);

        }
        return cart;
    }

    /**
     * 获取购物车商品信息
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String,Object,Object> hasOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hasOps.values();
        if (values != null && values.size() > 0){
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 删除购物车
     * @param cartKey
     */
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 购物项是否选中
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**
     * 数量设置
     * @param skuId
     * @param num
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**
     * 删除商品
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取当前用户的购物车商品
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            //获取有被选中的购物项
            List<CartItem> checkedItems = cartItems.stream()
                    .filter(cartItem -> cartItem.getCheck())
                    .map(item->{
                        //更新为最新价格
                        item.setPrice(productFeignService.getPrice(item.getSkuId()));
                        return item;
                    })
                    .collect(Collectors.toList());
            return checkedItems;
        }
    }
}
